# -*- coding: utf-8 -*- 
import cv2
import time
import os
import face_recognition
import time
import pickle
from flask import jsonify
# import RPi.GPIO as GPIO

class face_detector():
    def __init__(self,results=[]):
        self.image_extensions = ['png', 'jpg', 'jpeg', 'gif']
        self.process_this_frame = True
        self.location = 'results.pkl'
        self.monitor = 17
        if len(results) >0:
            self.results = self.load_weigth()
        else:
            self.results = results
        self.video_capture = cv2.VideoCapture(0)

    def load_weigth(self):
        if os.path.exists(self.location):
            with open(self.location,'rb') as f:
                results = pickle.load(f)

        else:
            results = self.save_weigth(self.location)
        return results

    def save_weigth(self):
        results = self.load_faces("./images/")
        with open(self.location, 'wb') as f:
            pickle.dump(results, f)
    

    def load_faces(self, path):
        print("loading training data")
        image_extensions = self.image_extensions
        names = [i for i in os.listdir(path) if "." not in i]
        known_names = []
        known_encodings = []
        for name in names:
            sub_path = os.path.join(path, name)
            for image_name in os.listdir(sub_path):
                if image_name.rsplit(".")[1].lower() in image_extensions:
                    load_image = face_recognition.load_image_file(os.path.join(sub_path, image_name))
                    face_feature = face_recognition.face_encodings(load_image)
                    if len(face_feature) > 0:
                        image_face_encoding = face_feature[0]
                        known_names.append(name)
                        known_encodings.append(image_face_encoding)
        return known_names, known_encodings

    def countFace(self):
        cap = cv2.VideoCapture(0)
        ret, frame = cap.read()
        rgb_frame = frame[:, :, ::-1]
        known_names = self.results[0]
        known_encodings = self.results[1]
        if self.process_this_frame:
            face_locations = face_recognition.face_locations(rgb_frame)  # 获得所有人脸位置
            face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)  # 获得人脸特征值
            face_names = []
            for face_encoding in face_encodings:
                matches = face_recognition.compare_faces(known_encodings, face_encoding, tolerance=0.5)
                if True in matches:
                    first_match_index = matches.index(True)
                    name = known_names[first_match_index]
                else:
                    name = "unknown"
                face_names.append(name)
            return [len(face_names),list(set(face_names))]

if __name__ == '__main__':
    with open("results.pkl", 'rb') as f:
        results = pickle.load(f)
    known_face_encodings = results[1]
    known_face_names  = results[0]
    face_locations = []
    face_encodings = []
    face_names = []
    process_this_frame = True

    while True:
        # Grab a single frame of video
        video_capture = cv2.VideoCapture(0)
        ret, frame = video_capture.read()

        # Resize frame of video to 1/4 size for faster face recognition processing
        small_frame = frame

        # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
        rgb_small_frame = small_frame[:, :, ::-1]

        # Only process every other frame of video to save time
        if True:
            # Find all the faces and face encodings in the current frame of video
            face_locations = face_recognition.face_locations(rgb_small_frame)
            face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)

            face_names = []
            for face_encoding in face_encodings:
                # See if the face is a match for the known face(s)
                matches = face_recognition.compare_faces(known_face_encodings, face_encoding,tolerance=0.6)
                name = "Unknown"

                # If a match was found in known_face_encodings, just use the first one.
                if True in matches:
                    first_match_index = matches.index(True)
                    name = known_face_names[first_match_index]

                face_names.append(name)

        process_this_frame = not process_this_frame
        [len(face_names), list(set(face_names))]
        # Display the results
        for (top, right, bottom, left), name in zip(face_locations, face_names):
            # Scale back up face locations since the frame we detected in was scaled to 1/4 size

            # Draw a box around the face
            cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)

            # Draw a label with a name below the face
            cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
            font = cv2.FONT_HERSHEY_DUPLEX
            cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)

        # Display the resulting image
        cv2.imshow('Video', frame)
        with open("result_keep.txt",'a') as f:
            content_format = "{0};{1}\n"
            content = content_format.format(len(face_names), list(set(face_names)))
            f.write(content)
            f.close()
        # Hit 'q' on the keyboard to quit!
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    # Release handle to the webcam
    video_capture.release()
    cv2.destroyAllWindows()